package com.risk.management.controller;

import com.risk.management.dto.Result;
import com.risk.management.entity.Risk;
import com.risk.management.entity.RiskResponse;
import com.risk.management.entity.User;
import com.risk.management.service.RiskResponseService;
import com.risk.management.service.RiskService;
import com.risk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
// 恢复Spring Security依赖
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 风险响应计划控制器
 */
@Controller
@RequestMapping("/risk-response")
public class RiskResponseController {

    @Autowired
    private RiskResponseService riskResponseService;

    @Autowired
    private RiskService riskService;

    @Autowired
    private UserService userService;

    /**
     * 风险响应计划列表 (用于HTML视图)
     */
    @GetMapping("/risk/{riskId}")
    public String listByRisk(@PathVariable Long riskId, Model model) {
        Risk risk = riskService.getRiskById(riskId);
        if (risk == null) {
            return "redirect:/risk/list";
        }
        
        List<RiskResponse> responses = riskResponseService.getRiskResponsesByRiskId(riskId);
        model.addAttribute("risk", risk);
        model.addAttribute("responses", responses);
        return "response/list";
    }
    
    /**
     * 风险响应计划列表片段 (用于AJAX加载)
     */
    @GetMapping("/list/{riskId}")
    public String listPartial(@PathVariable Long riskId, Model model) {
        Risk risk = riskService.getRiskById(riskId);
        if (risk == null) {
            return "fragments/empty";
        }
        
        List<RiskResponse> responses = riskResponseService.getRiskResponsesByRiskId(riskId);
        // 设置响应计划的额外信息
        for (RiskResponse response : responses) {
            // 设置风险标题（用于显示）
            response.setRiskTitle(risk.getTitle());
            
            // 获取并设置负责人名称（用于显示）
            User responsible = userService.getUserById(response.getResponsibleId());
            if (responsible != null) {
                response.setResponsibleName(responsible.getRealName());
            }
        }
        
        model.addAttribute("risk", risk);
        model.addAttribute("responses", responses);
        return "fragments/response-list";
    }

    /**
     * 我负责的响应计划 - 使用Spring Security获取当前用户
     */
    @GetMapping("/my")
    public String myResponses(@AuthenticationPrincipal UserDetails userDetails, Model model) {
        // 验证用户
        if (userDetails == null) {
            return "redirect:/risk/list";
        }
        
        User user = userService.getUserByUsername(userDetails.getUsername());
        if (user == null) {
            return "redirect:/risk/list";
        }
        
        List<RiskResponse> responses = riskResponseService.getRiskResponsesByResponsibleId(user.getId());
        model.addAttribute("responses", responses);
        return "response/my";
    }

    /**
     * 响应计划详情
     */
    @GetMapping("/{id}")
    public String detail(@PathVariable Long id, Model model) {
        RiskResponse response = riskResponseService.getRiskResponseById(id);
        if (response == null) {
            return "redirect:/risk/list";
        }
        
        model.addAttribute("response", response);
        
        // 获取风险信息
        Risk risk = riskService.getRiskById(response.getRiskId());
        model.addAttribute("risk", risk);
        
        // 获取负责人信息
        User responsible = userService.getUserById(response.getResponsibleId());
        model.addAttribute("responsible", responsible);
        
        return "response/detail";
    }

    /**
     * 新增响应计划页面
     */
    @GetMapping("/add")
    public String add(@RequestParam Long riskId, Model model) {
        Risk risk = riskService.getRiskById(riskId);
        if (risk == null) {
            return "redirect:/risk/list";
        }
        
        model.addAttribute("risk", risk);
        
        // 获取所有用户（作为负责人候选）
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        
        return "response/add";
    }

    /**
     * 新增响应计划
     */
    @PostMapping("/add")
    @ResponseBody
    public Result<Void> add(@RequestBody RiskResponse response) {
        boolean success = riskResponseService.addRiskResponse(response);
        if (success) {
            // 更新风险状态为已计划
            riskService.updateRiskStatus(response.getRiskId(), 3);
            return Result.success();
        } else {
            return Result.error("添加响应计划失败");
        }
    }

    /**
     * 编辑响应计划页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        RiskResponse response = riskResponseService.getRiskResponseById(id);
        if (response == null) {
            return "redirect:/risk/list";
        }
        
        model.addAttribute("response", response);
        
        // 获取风险信息
        Risk risk = riskService.getRiskById(response.getRiskId());
        model.addAttribute("risk", risk);
        
        // 获取所有用户（作为负责人候选）
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        
        return "response/edit";
    }

    /**
     * 编辑响应计划
     */
    @PostMapping("/edit")
    @ResponseBody
    public Result<Void> edit(@RequestBody RiskResponse response) {
        boolean success = riskResponseService.updateRiskResponse(response);
        if (success) {
            return Result.success();
        } else {
            return Result.error("更新响应计划失败");
        }
    }

    /**
     * 删除响应计划
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        RiskResponse response = riskResponseService.getRiskResponseById(id);
        if (response == null) {
            return Result.error("响应计划不存在");
        }
        
        boolean success = riskResponseService.deleteRiskResponse(id);
        if (success) {
            // 检查是否还有其他响应计划
            List<RiskResponse> responses = riskResponseService.getRiskResponsesByRiskId(response.getRiskId());
            if (responses.isEmpty()) {
                // 如果没有其他响应计划，将风险状态改回已分析
                riskService.updateRiskStatus(response.getRiskId(), 2);
            }
            return Result.success();
        } else {
            return Result.error("删除响应计划失败");
        }
    }

    /**
     * 更新响应计划状态
     */
    @PostMapping("/status/{id}/{status}")
    @ResponseBody
    public Result<Void> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        RiskResponse response = riskResponseService.getRiskResponseById(id);
        if (response == null) {
            return Result.error("响应计划不存在");
        }
        
        boolean success = riskResponseService.updateRiskResponseStatus(id, status);
        if (success) {
            // 如果状态更新为已完成，更新风险状态
            if (status == 3) {
                // 检查是否所有响应计划都已完成
                List<RiskResponse> responses = riskResponseService.getRiskResponsesByRiskId(response.getRiskId());
                boolean allCompleted = responses.stream().allMatch(r -> r.getStatus() != null && r.getStatus() == 3);
                
                if (allCompleted) {
                    // 如果所有计划都已完成，将风险状态更新为已解决
                    riskService.updateRiskStatus(response.getRiskId(), 5);
                } else {
                    // 否则更新为已处理
                    riskService.updateRiskStatus(response.getRiskId(), 4);
                }
            }
            return Result.success();
        } else {
            return Result.error("更新响应计划状态失败");
        }
    }

    /**
     * 更新实际完成时间
     */
    @PostMapping("/actual-end-time/{id}")
    @ResponseBody
    public Result<Void> updateActualEndTime(
            @PathVariable Long id, 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date actualEndTime) {
        boolean success = riskResponseService.updateRiskResponseActualEndTime(id, actualEndTime);
        if (success) {
            // 同时将状态更新为已完成
            riskResponseService.updateRiskResponseStatus(id, 3);
            return Result.success();
        } else {
            return Result.error("更新实际完成时间失败");
        }
    }
} 